package com.sanery.ui.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sanery.entity.User;
import com.sanery.service.UserService;

@Controller
public class UserController {

	@Autowired
	@Qualifier("uservice")
	private UserService uservice;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String username, String password, HttpSession session) {
		username = username.trim();
		password = password.trim();
		if (username.isEmpty() || password.isEmpty()) {
			return "/login";
		} else {
			User user = uservice.getUser(username, password);
			System.out.println(user);
			if (user != null) {
				session.setAttribute("user", user);
				return "redirect:/index";
			}
			return "/login";
		}
	}

	@RequestMapping("logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/login";
	}
}
